<template>
  <div>
    <el-card>
      <div class="card-wrap">
        <el-page-header @back="goBack(false)" content="创建项目">
        </el-page-header>
        <div>
          <el-button @click="goBack(false)">取消</el-button>
          <template v-if="!isApproval && !isChange && !isStop">
            <el-button
              v-if="!route.query.instanceId"
              :loading="state.saveLoading"
              type="primary"
              @click="handleSave(true, '1')"
              >保存</el-button
            >
            <el-button
              v-if="state.formData.saveStatus === '1' || !isApproval"
              type="primary"
              :loading="state.saveLoading"
              @click="handleSubmit"
              >提交</el-button
            >
          </template>

          <template v-if="isChange">
            <el-button type="primary" @click="handleChange">提交变更</el-button>
          </template>
          <template v-if="isStop">
            <el-button type="primary" @click="handleStop">提交终止</el-button>
          </template>
        </div>
      </div>
    </el-card>
    <br />
    <el-form
      :model="state.formData"
      ref="formRef"
      @submit.prevent
      :rules="formRules"
      label-width="140px"
    >
      <el-card>
        <template #header>
          <div class="card-box-header">
            <span>项目基础信息</span>
            <div v-if="show1" @click="show1 = !show1" class="header-btn">
              收起
              <i class="el-icon-arrow-down"></i>
            </div>
            <div v-else @click="show1 = !show1" class="header-btn">
              展开
              <i class="el-icon-arrow-right"></i>
            </div>
          </div>
        </template>
        <el-collapse-transition>
          <div v-show="show1">
            <el-row>
              <el-col :xl="8" :lg="12">
                <el-form-item label="项目名称" prop="projectName">
                  <el-input
                    :disabled="isApproval"
                    v-model.trim="state.formData.projectName"
                    class="width-custom"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :xl="8" :lg="12" v-if="showProjectNumber">
                <el-form-item label="项目编号">
                  <el-input
                    disabled
                    v-model.trim="state.formData.projectCode"
                    class="width-custom"
                  ></el-input>
                </el-form-item>
              </el-col>

              <el-col :xl="8" :lg="12">
                <el-form-item label="备用项目编号">
                  <el-input
                    v-model.trim="state.formData.projectCodeBackup"
                    class="width-custom"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :xl="8" :lg="12">
                <el-form-item label="项目审批类型" prop="approveTypeMaxCode">
                  <el-select
                    :disabled="isApproval"
                    v-model="state.formData.approveTypeMaxCode"
                    clearable
                    style="width: 100%"
                    value-key="dicCode"
                  >
                    <el-option
                      id="default-option"
                      v-for="item in projectApproveTypeArr"
                      :key="item.dicCode"
                      :label="item.dicValue"
                      :value="item"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :xl="8" :lg="12" class="approve-code">
                <el-form-item label="" prop="approveTypeMinCode">
                  <el-select
                    :disabled="isApproval"
                    v-model="state.formData.approveTypeMinCode"
                    clearable
                    style="width: 100%"
                    value-key="dicCode"
                  >
                    <el-option
                      id="default-option"
                      v-for="item in projectApproveTypeArr2"
                      :key="item.dicCode"
                      :label="item.dicValue"
                      :value="item"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :xl="8" :lg="12">
                <el-form-item label="项目开始时间" prop="ext1">
                  <el-date-picker
                    :disabled="isApproval"
                    style="width: 100%"
                    v-model="state.formData.ext1"
                    value-format="YYYY-MM-DD hh:mm:ss"
                    type="date"
                  />
                </el-form-item>
              </el-col>
              <el-col :xl="8" :lg="12">
                <el-form-item label="项目预计验收时间" prop="ext2">
                  <el-date-picker
                    :disabled="isApproval"
                    style="width: 100%"
                    v-model="state.formData.ext2"
                    value-format="YYYY-MM-DD hh:mm:ss"
                    type="date"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :xl="8" :lg="12">
                <el-form-item label="项目类型" prop="projectTypeCode">
                  <el-select
                    :disabled="isApproval"
                    v-model="state.formData.projectTypeCode"
                    clearable
                    style="width: 100%"
                    value-key="dicCode"
                  >
                    <el-option
                      id="default-option"
                      v-for="item in projectTypeArr"
                      :key="item.dicCode"
                      :label="item.dicValue"
                      :value="item"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :xl="8" :lg="12">
                <el-form-item label="所属公司主体" prop="principalCompanyCode">
                  <el-select
                    :disabled="isApproval"
                    v-model="state.formData.principalCompanyCode"
                    clearable
                    style="width: 100%"
                    value-key="dicCode"
                  >
                    <el-option
                      id="default-option"
                      v-for="item in principalCompanyArr"
                      :key="item.dicCode"
                      :label="item.dicValue"
                      :value="item"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :xl="8" :lg="12">
                <el-form-item label="项目负责人" prop="projectLeaderId">
                  <el-select
                    :disabled="isApproval"
                    v-model="state.formData.projectLeaderId"
                    style="width: 100%"
                    filterable
                    clearable
                    remote
                    placeholder="请输入姓名搜索"
                    :remote-method="getTableLeaderData"
                    value-key="id"
                    @change="changeLeader"
                  >
                    <el-option
                      id="default-option"
                      v-for="item in userList"
                      :key="item.id"
                      :label="item.name"
                      :value="item"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :xl="8" :lg="12">
                <el-form-item label="项目联系人" prop="projectOwner">
                  <el-select
                    :disabled="isApproval"
                    v-model="state.formData.projectOwner"
                    style="width: 100%"
                    filterable
                    clearable
                    remote
                    placeholder="请输入姓名搜索"
                    :remote-method="getTableLeaderData2"
                    value-key="id"
                    @change="changeOwner"
                  >
                    <el-option
                      id="default-option"
                      v-for="item in userList2"
                      :key="item.id"
                      :label="item.name"
                      :value="item"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :xl="10" :lg="12">
                <el-row>
                  <el-col :xl="4" :lg="4"></el-col>
                  <el-col
                    :xl="8"
                    :lg="8"
                    v-if="state.formData.projectLeaderPhone"
                  >
                    <p class="p-text">
                      电话：{{ state.formData.projectLeaderPhone }}
                    </p>
                  </el-col>
                  <el-col :span="12" v-if="state.formData.projectLeaderEmail">
                    <p class="p-text">
                      邮箱：{{ state.formData.projectLeaderEmail }}
                    </p>
                  </el-col>
                </el-row>
              </el-col>

              <el-col :xl="10" :lg="10">
                <el-row>
                  <el-col :xl="4" :lg="4"></el-col>
                  <el-col
                    :xl="8"
                    :lg="8"
                    v-if="state.formData.projectContactPhone"
                  >
                    <p class="p-text">
                      电话：{{ state.formData.projectContactPhone }}
                    </p>
                  </el-col>
                  <el-col :span="8" v-if="state.formData.projectContactEmail">
                    <p class="p-text">
                      邮箱：{{ state.formData.projectContactEmail }}
                    </p>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>

            <el-row>
              <el-col :xl="16" :lg="24">
                <el-form-item label=" 是否含可行性研究" prop="isFsbStudy">
                  <el-radio-group
                    :disabled="isApproval"
                    v-model="state.formData.isFsbStudy"
                  >
                    <el-radio label="1" size="small"> 是</el-radio>
                    <el-radio label="0" size="small">否</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :xl="16" :lg="24">
                <el-form-item label="项目立项书" prop="projectProposalArr">
                  <ecm-upload
                    :files="defaultProposaFileList"
                    :docid="state.docid"
                    @setFile="handleProposaSuccess"
                  >
                    <template #temp>
                      <el-link
                        v-if="
                          state.formData.approveTypeMaxCode &&
                          state.formData.approveTypeMaxCode.dicCode !== '4'
                        "
                        style="margin-left: 16px"
                        type="primary"
                        @click="
                          postDownload('研发项目申报书（简化版）-模版.docx')
                        "
                        >研发项目申报书（简化版）-模版.docx
                      </el-link>
                      <el-link
                        v-if="
                          state.formData.approveTypeMaxCode &&
                          state.formData.approveTypeMaxCode.dicCode === '4'
                        "
                        style="margin-left: 16px"
                        type="primary"
                        @click="
                          postDownload('预研项目申报书（简化版）-模版.docx')
                        "
                        >预研项目申报书（简化版）-模版.docx
                      </el-link>
                    </template>
                  </ecm-upload>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :xl="16" :lg="24">
                <el-form-item label="项目其他申报材料" prop="kyFiles">
                  <ecm-upload
                    :files="defaultFileList"
                    :docid="state.docid"
                    @setFile="handleSuccess"
                  ></ecm-upload>
                </el-form-item>
              </el-col>
            </el-row>

            <!-- <el-row>
              <el-col :span="11">
                <el-form-item label="项目其他申报材料" prop="kyFiles">
                  <el-upload :disabled="isApproval" name="uploadFile" multiple :accept="acceptTypes"
                    :action="uploadComUrl" :headers="uploadHeaders" :on-success="handleSuccess" :on-remove="handleRemove"
                    :on-error="handleError" :file-list="defaultFileList" :before-upload="beforeAvatarUpload"
                    :on-preview="handlePreview">
                    <el-button v-if="!isApproval" size="small" type="primary">点击上传</el-button>
                    <template #tip>
                      <div class="el-upload__tip">
                        支持上传doc、docx、xls、xlsx、pdf、ppt、pptx、png、jpg、jpeg等格式文件,文件大小不得大于10M。
                      </div>
                    </template>
                  </el-upload>
                </el-form-item>
              </el-col>
            </el-row> -->
          </div>
        </el-collapse-transition>
      </el-card>

      <br />

      <el-card>
        <template #header>
          <div class="card-box-header">
            <span>项目目标及考核指标</span>
            <div v-if="show2" @click="show2 = !show2" class="header-btn">
              收起
              <i class="el-icon-arrow-down"></i>
            </div>
            <div v-else @click="show2 = !show2" class="header-btn">
              展开
              <i class="el-icon-arrow-right"></i>
            </div>
          </div>
        </template>
        <div v-show="show2">
          <Goal :data="state.formData.projectTargetList" ref="goal" />
        </div>
      </el-card>

      <br />
      <el-card>
        <template #header>
          <div class="card-box-header">
            <span>项目承担单位</span>
            <div v-if="show3" @click="show3 = !show3" class="header-btn">
              收起
              <i class="el-icon-arrow-down"></i>
            </div>
            <div v-else @click="show3 = !show3" class="header-btn">
              展开
              <i class="el-icon-arrow-right"></i>
            </div>
          </div>
        </template>
        <div v-show="show3">
          <Company
            :data="state.formData.projectUnderUnit"
            ref="company"
            @change="changeCompany"
          />
        </div>
      </el-card>
      <br />
      <el-card>
        <template #header>
          <div class="card-box-header">
            <span>项目团队成员</span>
            <div v-if="show4" @click="show4 = !show4" class="header-btn">
              收起
              <i class="el-icon-arrow-down"></i>
            </div>
            <div v-else @click="show4 = !show4" class="header-btn">
              展开
              <i class="el-icon-arrow-right"></i>
            </div>
          </div>
        </template>
        <div v-show="show4">
          <Member
            ref="meber"
            :leader="String(state.leaderId)"
            :owner="String(state.ownerId)"
            :data="state.formData.projectMemberList"
          />
        </div>
      </el-card>

      <br />
      <el-card>
        <template #header>
          <div class="card-box-header">
            <span>项目实施计划</span>
            <div v-if="show5" @click="show5 = !show5" class="header-btn">
              收起
              <i class="el-icon-arrow-down"></i>
            </div>
            <div v-else @click="show5 = !show5" class="header-btn">
              展开
              <i class="el-icon-arrow-right"></i>
            </div>
          </div>
        </template>
        <div v-show="show5">
          <Plan
            ref="plan"
            :data="state.formData.projectPlan"
            :startTime="state.formData.ext1"
            :endTime="state.formData.ext2"
          />
        </div>
      </el-card>

      <br />
      <el-card>
        <template #header>
          <div class="card-box-header">
            <span>科创管理人员</span>
            <div v-if="show6" @click="show6 = !show6" class="header-btn">
              收起
              <i class="el-icon-arrow-down"></i>
            </div>
            <div v-else @click="show6 = !show6" class="header-btn">
              展开
              <i class="el-icon-arrow-right"></i>
            </div>
          </div>
        </template>
        <div v-show="show6">
          <sci-tech
            ref="sciTech"
            :data="state.formData.projectSciTecList"
          />
        </div>
      </el-card>

      <!-- <br />
      <el-card>
        <template #header>
          <div class="card-box-header">
            <span>项目经费预算<span style="color: red; margin-left: 10px; font-size: 14px">请注意：填报金额单位为 元（人民币）。</span></span>
            <div v-if="show6" @click="show6 = !show6" class="header-btn">
              收起
              <i class="el-icon-arrow-down"></i>
            </div>
            <div v-else @click="show6 = !show6" class="header-btn">
              展开
              <i class="el-icon-arrow-right"></i>
            </div>
          </div>
        </template>
        <div v-show="show6">
          <Funds ref="funds" @updateFiles="updateFiles" :companyList="state.fundsCompanyList" />
        </div>
      </el-card> -->
    </el-form>
  </div>
  <!-- <el-dialog
    :show-close="false"
    title="变更信息"
    v-model="state.changeDialogFormVisible"
    destroy-on-close
    width="45vw"
  >
    <changeDialog @cancel="goBack(false)" @submit="submitChange" />
  </el-dialog> -->

  <approveDialog
    v-if="approveDialogVisiable"
    :nodeId="nodeId"
    :flowType="state.changeflowType"
    @cancel="approveDialogVisiable = false"
    @sure="sureSubmit"
  ></approveDialog>
</template>

<script lang="ts" setup>
import approveDialog from "/@/components/approveDialog/index.vue";
import { ref, reactive, onMounted, unref } from "vue";
import { useRouter, useRoute } from "vue-router";
import { cloneDeep } from "lodash-es";
import {
  postProjectAdd,
  getProjectInfo,
  postProjectUpdate,
  postProjectChange,
  // approveStage,
  approveProject,
  submitStage,
  // approveStage,
  // rejectStage,
  // approveProject,
  // rejectProject,
  postProjecStop,
  flowStart,
  flowSubmit
} from "/@/api/project";

import { getUsersForScience } from "/@/api/user";

import { postContractList } from "/@/api/contract";

import { postDictList } from "/@/api/common";
import NotifMessage from "/@/utils/message/notification";

import Goal from "./components/goal.vue";
import Company from "./components/company.vue";
import Member from "./components/member.vue";
import Plan from "./components/plan.vue";
import SciTech from "./components/SciTech.vue";
// import Funds from "./components/Funds.vue";
import { useProjectStoreHook } from "/@/store/modules/project";
// import { getTableData } from "/@/components/treeTable/data";
import { flowTypeCode } from "./types";
import { storageLocal } from "/@/utils/storage";
import EcmUpload from "/@/components/ecmUpload/index.vue";
import { ElMessageBox } from "element-plus";

let defaultFileList = ref([]);
let defaultProposaFileList = ref([]);
let approveDialogVisiable = ref<boolean>(false); // 点击提交弹窗，选择下一步审批人
const formRef = ref<HTMLFormElement | null>(null) as any;
const goal = ref(null);
const meber = ref(null);
const company = ref(null);
const plan = ref(null);
const sciTech = ref(null);
const router = useRouter();
const route = useRoute();

let showProjectNumber = ref<boolean>(false);
let show1 = ref<boolean>(true);
let show2 = ref<boolean>(true);
let show3 = ref<boolean>(true);
let show4 = ref<boolean>(true);
let show5 = ref<boolean>(true);
let show6 = ref<boolean>(true);
const nodeId = route.query.nodeId ? route.query.nodeId : "ACT_010";
let state = reactive({
  docid: window["ecmDocType"].project,
  stageStatus: "0",
  reason: "", //变更原因
  changeflowType: "2028",
  flowType: "2028",
  changeDialogFormVisible: false,
  isSubmit: false,
  changeInfo: null,
  stopInfo: null,
  saveLoading: false,
  projectManageId: null,
  formData: {
    saveStatus: "",
    projectName: "",
    projectCode: "",
    projectCodeBackup:"",
    projectTypeCode: null,
    projectTypeName: "",
    projectLeaderId: null,
    projectLeaderName: "",
    projectContractDTOList: [],
    // checkMember: [], //项目成员
    projectMemberList: [],
    reviewExpertList: [],
    // checkReview: [], //评审专家
    projectTotalFunds: null, // 项目总经费
    projectOwner: null,
    ext1: "", // 项目开始时间
    ext2: "", // 项目结束时间
    ext3: "", // 项目联系人id
    ext4: "", // 项目联系人name
    ext5: null, // 实际经费
    projectLeaderPhone: "",
    projectLeaderEmail: "",
    projectContactPhone: "",
    projectContactEmail: "",
    kyFiles: [],
    projectProposalArr: [],
    projectTargetList: [],
    projectUnderUnit: [],
    projectPlan: [],
    projectSciTecList:[],
    approvalTypeName: "",
    isFsbStudy: "1",
    principalCompanyCode: null,
    approveTypeMaxCode: null,
    approveTypeMinCode: null
  },
  tableData: [],
  contractInfo: {},
  contractIndex: 0,
  fundsTableData: [],
  fundsCompanyList: [],
  deptFiles: {},
  fundsInfo: {},
  fundsIndex: 0,
  tableDataChangeAdd: [],
  milepostList: [],
  leaderId: "",
  ownerId: ""
});

let projectTypeArr = ref([]);
let projectApproveTypeArr = ref([]);
let projectApproveTypeArr2 = ref([]);

let principalCompanyArr = ref([]);

let userList = ref([]);
let userList2 = ref([]);

// const milepostFormRules = ref({
//   name: [{ required: true, message: "请输入阶段名称", trigger: "change" }],
//   time: [{ required: true, message: "请选择阶段起止时间", trigger: "change" }],
//   des1: [{ required: true, message: "请输入研究内容", trigger: "change" }],
//   des2: [{ required: true, message: "请输入预期目标", trigger: "change" }]
// });

const formRules = ref({
  projectName: [{ required: true, message: "请输入名称", trigger: "change" }],
  projectTypeCode: [
    { required: true, message: "请选择类型", trigger: "change" }
  ],
  projectLeaderId: [
    { required: true, message: "请选择负责人", trigger: "change" }
  ],

  projectOwner: [
    { required: true, message: "请选择联系人", trigger: "change" }
  ],
  ext1: [{ required: true, message: "请选择项目开始时间", trigger: "change" }],
  ext2: [
    { required: true, message: "请选择项目预计验收时间", trigger: "change" }
  ],

  // projectProposalArr: [
  //   { required: true, message: "请上传项目立项书", trigger: "change" }
  // ],

  approveTypeMaxCode: [
    { required: true, message: "请选择项目审批类型", trigger: "change" }
  ],
  approveTypeMinCode: [
    { required: true, message: "请选择项目审批类型", trigger: "change" }
  ],
  isFsbStudy: [
    { required: true, message: "请选择是否含可行性研究", trigger: "change" }
  ],
  principalCompanyCode: [
    { required: true, message: "请选择所属公司主体", trigger: "change" }
  ]
});

//发起流程
const flowStartData = reactive({
  formBaseInfo: {
    billName: "",
    projectName: "",
    projectManageId: route.query.id,
    id: route.query.id,
    flowStartAttachmentArr: []
  },
  flowFormData: {
    businessId: route.query.id,
    flowTypeCode: "",
    nodeId: route.query.nodeId,
    projectManageId: route.query.id,
    remarks: "",
    saveState: "1"
  },
  formSubMap: {
    stageStatus: "0",
    flowType: "",
    assignee: null,
    opinion: ""
  }
});

const postDownload = fileName => {
  window.open(`${location.origin}${location.pathname}/${fileName}`);
};

const handleSuccess = res => {
  defaultFileList.value = res.file;
  state.formData.kyFiles = res.file;
  formRef.value.clearValidate();
};
const handleProposaSuccess = res => {
  defaultProposaFileList.value = res.file;
  state.formData.projectProposalArr = res.file;
  formRef.value.clearValidate();
};

// 初始化请求
const initProjectTypeList = async () => {
  try {
    const params = {
      dicType: "rd_project_type"
    };
    const { code, data } = await postDictList(params);
    if (code === 200) {
      projectTypeArr.value = data;
    }
  } catch (err) {
    console.log(err);
  }
};

const initPrincipalCompanyList = async () => {
  try {
    const params = {
      dicType: "rd_principal_cmpy"
    };
    const { code, data } = await postDictList(params);
    if (code === 200) {
      principalCompanyArr.value = data;
    }
  } catch (err) {
    console.log(err);
  }
};

const initProjectApprovalTypeList = async () => {
  try {
    const params = {
      dicType: "rd_pro_approve_max_type"
    };
    const { code, data } = await postDictList(params);
    if (code === 200) {
      projectApproveTypeArr.value = data;
    }
  } catch (err) {
    console.log(err);
  }
};
const initProjectApprovalTypeList2 = async () => {
  try {
    const params = {
      dicType: "rd_pro_approve_min_type"
    };
    const { code, data } = await postDictList(params);
    if (code === 200) {
      projectApproveTypeArr2.value = data;
    }
  } catch (err) {
    console.log(err);
  }
};

async function getTableLeaderData(query = "") {
  if (!query) {
    userList.value = [];
    return;
  }
  try {
    const params = {
      pageNum: 1,
      pageSize: 200,
      name: query
    };
    const { code, data } = await getUsersForScience(params);
    if (code === 200) {
      userList.value = data.list.map(item => {
        return {
          id: item.id,
          name: item.name + (item.deptName ? "-" + item.deptName : "-无"),
          phoneNum: item.phoneNum,
          email: item.email,
          companyName: item.deptName
        };
      });
    }
  } catch (err) {
    console.log(err);
  }
}

async function getTableLeaderData2(query = "") {
  if (!query) {
    userList.value = [];
    return;
  }
  try {
    const params = {
      pageNum: 1,
      pageSize: 200,
      name: query
    };
    const { code, data } = await getUsersForScience(params);
    if (code === 200) {
      userList2.value = data.list.map(item => {
        return {
          id: item.id,
          name: item.name + (item.deptName ? "-" + item.deptName : "-无"),
          phoneNum: item.phoneNum,
          email: item.email,
          companyName: item.deptName
        };
      });
    }
  } catch (err) {
    console.log(err);
  }
}

//

const goBack = async (flag = true) => {
  console.log(flag);
  router.push("/project/manage");
};

const flowSumbitStart = async () => {
  await approveProject(route.query.id);

  await submitStage(route.query.id);

  flowStartData.formBaseInfo.billName =
    state.formData.projectName + "-项目建档-审批流程";
  flowStartData.formBaseInfo.projectName = state.formData.projectName;

  flowStartData.flowFormData.flowTypeCode = state.flowType;

  flowStartData.formBaseInfo.projectManageId = state.projectManageId;
  flowStartData.formBaseInfo.id = state.projectManageId;

  flowStartData.flowFormData.projectManageId = state.projectManageId;
  flowStartData.flowFormData.businessId = state.projectManageId;
  flowStartData.formSubMap.flowType = state.flowType;
  flowStartData.formSubMap.assignee = state.leaderId;

  const { code, message } = await flowStart(flowStartData);
  if (code === 200) {
    state.saveLoading = false;
    NotifMessage.success(message);
    goBack();
  }
};

const flowPassData = reactive({
  formBaseInfo: {
    id: route.query.id,
    acceptUsers: null
  },
  flowFormData: {
    approvalComments: "",
    approvalResult: "",
    businessId: route.query.id,
    flowId: route.query.flowId,
    flowTypeCode: "",
    instanceId: route.query.instanceId,
    nodeId: route.query.nodeId,
    remarks: "",
    saveState: "1"
  },
  formSubMap: {
    stageStatus: "0",
    flowType: "",
    nodeId: route.query.nodeId,
    procInstId: route.query.instanceId,
    taskId: route.query.taskId,
    opinion: "",
    assignee: null,
    isChargehand: "1", //1：向下提交到下一步：0：回退到某一步
    specialReject: "0"
  },
  tmpStorage: {
    nodeId: route.query.nodeId,
    flowId: route.query.flowId,
    taskId: route.query.taskId,
    handlerId: null,
    valueJson: ""
  }
});

const flowPassSubmit = async () => {
  flowPassData.flowFormData.approvalComments = "";
  flowPassData.flowFormData.approvalResult = "1"; //同意：1，不同意：0
  flowPassData.flowFormData.remarks = "";
  flowPassData.flowFormData.flowTypeCode = state.flowType;
  flowPassData.formSubMap.opinion = ``;
  flowPassData.tmpStorage.valueJson = JSON.stringify(flowPassData.formSubMap);
  const info = storageLocal.getItem("rdms-info");
  const userId = info?.userId;
  flowPassData.tmpStorage.handlerId = userId;
  flowPassData.formBaseInfo.acceptUsers = state.leaderId;
  flowPassData.formSubMap.assignee = state.leaderId;
  flowPassData.formSubMap.isChargehand = "1";
  flowPassData.formSubMap.flowType = state.flowType;
  const { code, message } = await flowSubmit(flowPassData);
  if (code === 200) {
    NotifMessage.success(message);
    router.push("/approval/todo");
    // goBack();
  } else {
    NotifMessage.error(message);
  }
};

const handleSubmit = async () => {
  const txt = state.formData.isFsbStudy==1?'':'不'
  ElMessageBox.confirm(`确认${txt}执行可行性研究吗？`, "提示", {
    type:"warning"
  })
    .then(async () => {
      state.saveLoading = true;
      const flag = await handleSave(false, "2");
      if (flag == null) {
        state.saveLoading = false;
        return;
      }
      if (!flag) {
        if (
          route.query.instanceId &&
          (route.query.source === "back" || state.stageStatus === "0")
        ) {
          flowPassSubmit();
        } else {
          flowSumbitStart();
        }
      }
    })
    .catch(() => {
      
    });
};

const getSubmitParams = () => {
  const copyFormData = cloneDeep(state.formData);
  copyFormData.kyFiles = JSON.stringify(copyFormData.kyFiles);
  delete copyFormData.kyFilesArr;
  copyFormData.projectTypeCode = state.formData.projectTypeCode.dicCode;
  copyFormData.projectTypeName = state.formData.projectTypeCode.dicValue;

  copyFormData.approveTypeMaxCode = state.formData.approveTypeMaxCode.dicCode;
  copyFormData.approveTypeMaxName = state.formData.approveTypeMaxCode.dicValue;

  copyFormData.approveTypeMinCode = state.formData.approveTypeMinCode.dicCode;
  copyFormData.approveTypeMinName = state.formData.approveTypeMinCode.dicValue;

  copyFormData.projectLeaderId = state.formData.projectLeaderId.id;
  copyFormData.projectLeaderName = state.formData.projectLeaderId.name;
  copyFormData.ext3 = copyFormData.projectOwner.id;
  copyFormData.ext4 = copyFormData.projectOwner.name;
  copyFormData.projectTargetList = goal.value.model.tableData;
  copyFormData.projectMemberList = meber.value.model.tableData;
  copyFormData.projectSciTecList = sciTech.value.model.tableData;
  copyFormData.projectMemberList.forEach(el => {
    delete el.user;
  });

  copyFormData.projectSciTecList.forEach(el => {
    delete el.user;
  });
  copyFormData.projectPlans = plan.value.model.tableData.map(el => {
    return {
      startTime: el.timeObj[0] + " 00:00:00",
      endTime: el.timeObj[1] + " 00:00:00",
      researchContent: el.content,
      goal: el.goal,
      projectId: route.query.id,
      alterationType: el.alterationType,
      id: el.id
    };
  });

  // 上传的经费预算附件，保存在字段projectUnderUnit中
  let ids = Object.keys(state.deptFiles);
  company.value.model.tableData.forEach(item => {
    if (ids.indexOf(String(item.code)) > -1) {
      item.dFiles = state.deptFiles[item.code];
    }
  });
  copyFormData.projectUnderUnit = JSON.stringify(company.value.model.tableData);
  const { query } = unref(route);
  copyFormData.id = query.id;
  delete copyFormData.projectPlan;
  copyFormData["principalCompanyCode"] =
    state.formData.principalCompanyCode.dicCode;
  copyFormData["principalCompanyName"] =
    state.formData.principalCompanyCode.dicValue;

  return copyFormData;
};

const handleSave = async (flag = true, status: string): Promise<any> => {
  const isValid = await new Promise(resolve => formRef.value.validate(resolve));

  if (isValid) {
    try {
      state.saveLoading = true;
      const { query } = unref(route);
      const params = getSubmitParams();
      params["saveStatus"] = status;
      params["isFilings"] = "1";
      if (plan.value.model.tableData.length === 0) {
        NotifMessage.warning("至少添加一条项目实施计划！");
        state.saveLoading = false;
        return true;
      }
      if (query.mode === "edit") {
        params.clickStage = "10";
        const { code, message } = await postProjectUpdate(params);

        if (code === 200) {
          if (flag) {
            state.saveLoading = false;
            NotifMessage.success(message);
            goBack();
            return true;
          } else {
            return false;
          }
        }
      } else {
        const { code, message, data } = await postProjectAdd(params);
        if (code === 200) {
          route.query.id = data;
          state.projectManageId = data + "";
          if (flag) {
            state.saveLoading = false;
            NotifMessage.success(message);
            goBack();
            return true;
          } else {
            state.saveLoading = false;
            return false;
          }
        }
      }
    } catch (err) {
      state.saveLoading = false;
      return true;
    }
  }
};

const changeCompany = item => {
  state.fundsCompanyList = item.map((el: any) => {
    return {
      ...el,
      id: el.code,
      name: el.name + (el.legal ? "-" + el.legal : ""),
      deptName: el.name,
      dFiles: el.dFiles || []
    };
  });
};

const changeLeader = item => {
  if (item !== "") {
    state.leaderId = item.id;
    state.formData.projectLeaderPhone = item.phoneNum;
    state.formData.projectLeaderEmail = item.email;
    let index = meber.value.model.tableData.findIndex(el => el.leader === true);
    if (meber.value.model.tableData.findIndex(el => el.id === item.id) !== -1) {
      return;
    }

    if (index !== -1) {
      meber.value.model.tableData[index] = {
        name: item.name.split("-")[0],
        user: item,
        isEmp: item.isEmp,
        id: item.id,
        userId: item.id,
        department: item.companyName,
        ext1: "项目负责人",
        leader: true
      };
    } else {
      meber.value.model.tableData.push({
        name: item.name.split("-")[0],
        userId: item.id,
        id: item.id,
        user: item,
        isEmp: item.isEmp,
        department: item.companyName,
        ext1: "项目负责人",
        leader: true
      });
    }
  }
};
const changeOwner = item => {
  if (item !== "") {
    state.ownerId = item.id;
    state.formData.projectContactPhone = item.phoneNum;
    state.formData.projectContactEmail = item.email;
    state.formData.ext3 = item.id;
    state.formData.ext4 = item.name;
    let index = meber.value.model.tableData.findIndex(el => el.owner === true);
    if (meber.value.model.tableData.findIndex(el => el.id === item.id) !== -1)
      return;
    if (index !== -1) {
      meber.value.model.tableData[index] = {
        name: item.name.split("-")[0],
        user: item,
        isEmp: item.isEmp,
        userId: item.id,
        id: item.id,
        department: item.companyName,
        ext1: "项目联系人",
        leader: true
      };
    } else {
      meber.value.model.tableData.push({
        name: item.name.split("-")[0],
        userId: item.id,
        user: item,
        id: item.id,
        isEmp: item.isEmp,
        department: item.companyName,
        ext1: "项目联系人",
        leader: true
      });
    }
  }
};

//提交变更
const handleChange = async () => {
  const isValid = await new Promise(resolve => formRef.value.validate(resolve));
  if (!isValid) return;
  approveDialogVisiable.value = true;
};

// 确定发起变更流程
const sureSubmit = async params => {
  const emyp =
    state.formData.approveTypeMaxCode.dicCode +
    "," +
    state.formData.approveTypeMinCode.dicCode;
  state.changeflowType = flowTypeCode[emyp];
  console.log("params", params);
  if (isChange) {
    asyncChangeMethod(params);
  }
  if (isStop) {
    asyncStopMethod(params);
  }
  approveDialogVisiable.value = false;
};

const asyncChangeMethod = async (obj: any): Promise<any> => {
  let storeAuth = useProjectStoreHook();
  state.changeInfo = storeAuth.getChangeInfo;
  const params = getSubmitParams();
  const projectMemberList = params.projectMemberList;
  const projectSciTecList = params.projectSciTecList;
  let projectTargetList = params.projectTargetList;
  projectTargetList = projectTargetList.concat(goal.value.model.deleteList);
  const delList = plan.value.model.deleteList.map(el => {
    return {
      startTime: el.timeObj[0] + " 00:00:00",
      endTime: el.timeObj[1] + " 00:00:00",
      researchContent: el.content,
      goal: el.goal,
      projectId: route.query.id,
      alterationType: el.alterationType,
      id: el.id
    };
  });
  const projectPlanList = params.projectPlans.concat(delList);

  const projectChangeParamDTO = cloneDeep(state.changeInfo);
  const { code, data } = await postProjectChange({
    id: route.query.id,
    projectManageAlterationDTO: params,
    reason: state.changeInfo.alterationReason,
    projectChangeParamDTO,
    projectMemberList,
    projectSciTecList,
    projectTargetList,
    projectPlanList
  });
  if (code === 200) {
    const billName = state.changeInfo.ext1 === "1" ? "重大变更" : "一般变更";
    const submitParams = {
      formBaseInfo: {
        billName: `${state.formData.projectName}-${billName}-审批流程`,
        projectName: state.formData.projectName,
        projectManageId: route.query.id,
        id: data,
        flowStartAttachmentArr: []
      },
      flowFormData: {
        businessId: data,
        flowTypeCode:
          state.changeInfo.ext1 === "2" ? "2028" : state.changeflowType,
        nodeId: route.query.nodeId,
        projectManageId: route.query.id,
        remarks: obj.remark,
        saveState: "1"
      },
      formSubMap: {
        stageStatus: (flowStartData.formSubMap.stageStatus =
          state.changeInfo.ext1 === "1" ? "21" : "20"),
        flowType: state.changeInfo.ext1 === "2" ? "2028" : state.changeflowType,
        assignee: obj?.handlederId?.id,
        opinion: ``
      }
    };
    startProcess(submitParams);
  }
};

// 发起变更流程
const startProcess = async params => {
  state.saveLoading = true;
  const { code, message } = await flowStart(params);
  if (code === 200) {
    NotifMessage.success(message);
    goBack();
  } else {
    NotifMessage.error(message);
  }
};

const asyncStopMethod = async (obj): Promise<any> => {
  try {
    let storeAuth = useProjectStoreHook();
    state.stopInfo = storeAuth.getStopInfo;
    const params = getSubmitParams();
    const projectMemberList = params.projectMemberList;
    const projectSciTecList = params.projectSciTecList;
    const projectTargetList = params.projectTargetList;
    const projectChangeParamDTO = cloneDeep(state.stopInfo);
    projectChangeParamDTO.alterationSignRecord = JSON.stringify(
      state.stopInfo.alterationSignRecord
    );
    projectChangeParamDTO.otherFile = JSON.stringify(state.stopInfo.otherFile);

    const { code, data } = await postProjecStop({
      id: route.query.id,
      projectManageAlterationDTO: params,
      reason: "",
      projectChangeParamDTO,
      projectMemberList,
      projectSciTecList,
      projectTargetList
    });
    if (code === 200) {
      const submitParams = {
        formBaseInfo: {
          billName: `${state.formData.projectName}-项目终止-审批流程`,
          projectName: state.formData.projectName,
          projectManageId: route.query.id,
          id: data,
          flowStartAttachmentArr: []
        },
        flowFormData: {
          businessId: data,
          flowTypeCode: state.changeflowType,
          nodeId: route.query.nodeId,
          projectManageId: route.query.id,
          remarks: obj.remark,
          saveState: "1"
        },
        formSubMap: {
          stageStatus: "22",
          flowType: state.changeflowType,
          assignee: obj?.handlederId?.id,
          opinion: ``
        }
      };
      startProcess(submitParams);
    }
  } catch (err) {
    console.error(err);
  }
};

const handleStop = async () => {
  const isValid = await new Promise(resolve => formRef.value.validate(resolve));
  if (!isValid) return;
  approveDialogVisiable.value = true;
};

onMounted(() => {
  const { query } = unref(route);
  if (query.id) {
    state.projectManageId = query.id as string;
    showProjectNumber.value = true;
    initGetProjectInfo(query.id as string);

    initGetContractList(query.id as string);
  }
  let storeAuth = useProjectStoreHook();
  if (query.mode === "change") {
    state.changeDialogFormVisible = true;
    // state.changeInfo = storeAuth.changeInfo;
  }
  if (query.mode === "stop") {
    state.stopInfo = storeAuth.stopInfo;
  }
});

const initGetProjectInfo = async (id: number | string) => {
  const { code, data } = await getProjectInfo({ id });
  if (code === 200) {
    // debugger
    const copyFormData = cloneDeep(data);
    state.stageStatus = copyFormData.stageStatus;
    flowStartData.formBaseInfo.billName = copyFormData.projectName;
    flowStartData.formBaseInfo.projectName = copyFormData.projectName;
    state.formData.saveStatus = copyFormData.saveStatus;
    // flowStartData.flowFormData.flowTypeCode = copyFormData.approvalTypeCode;
    // flowStartData.formSubMap.flowType = copyFormData.approvalTypeCode;
    // state.flowType = copyFormData.approvalTypeCode;
    // copyFormData.saveStatus === "1"||
    state.isSubmit =
      (copyFormData.stageApproveStatus === "1" ||
        copyFormData.stageApproveStatus === "4") &&
      (copyFormData.saveStatus === "3" || copyFormData.saveStatus === "8");

    state.formData = copyFormData;
    state.formData.projectTypeCode = {
      dicCode: copyFormData.projectTypeCode,
      dicValue: copyFormData.projectTypeName
    };

    state.formData.approveTypeMaxCode = {
      dicCode: copyFormData.approveTypeMaxCode,
      dicValue: copyFormData.approveTypeMaxName
    };
    state.formData.approveTypeMinCode = {
      dicCode: copyFormData.approveTypeMinCode,
      dicValue: copyFormData.approveTypeMinName
    };
    state.formData.principalCompanyCode = {
      dicCode: copyFormData.principalCompanyCode,
      dicValue: copyFormData.principalCompanyName
    };

    state.leaderId = copyFormData.projectLeaderId;
    state.ownerId = copyFormData.ext3;

    state.formData.projectOwner = {
      id: +copyFormData.ext3,
      name: copyFormData.ext4
    };
    state.formData.projectLeaderId = {
      id: +copyFormData.projectLeaderId,
      name: copyFormData.projectLeaderName
    };

    userList.value = [
      state.formData.projectLeaderId,
      state.formData.projectOwner
    ];

    userList2.value = [
      state.formData.projectLeaderId,
      state.formData.projectOwner
    ];
    state.formData.projectUnderUnit = JSON.parse(copyFormData.projectUnderUnit);
    state.formData.projectPlan = copyFormData.projectPlans.map(el => {
      return {
        time: el.startTime.split(" ")[0] + "至" + el.endTime.split(" ")[0],
        timeObj: [el.startTime.split(" ")[0], el.endTime.split(" ")[0]],
        content: el.researchContent,
        goal: el.goal,
        id: el.id
      };
    });
    if (copyFormData.kyFiles) {
      state.formData.kyFiles = JSON.parse(copyFormData.kyFiles as any);
      defaultFileList.value = state.formData.kyFiles;
      defaultFileList.value.map(el => {
        el["name"] = el.fileName;
      });
    } else {
      state.formData.kyFiles = [];
    }
    // <template #default="{ row }"> {{ row.name }}-{{ row.legal }} </template>
    if (copyFormData.projectProposalArr) {
      defaultProposaFileList.value = copyFormData.projectProposalArr;
      defaultProposaFileList.value.map(el => {
        el["name"] = el.fileName;
      });
      // state.formData.projectProposalArr=
    } else {
      state.formData.projectProposalArr = [];
    }
    state.fundsCompanyList = state.formData.projectUnderUnit.map((el: any) => {
      return {
        ...el,
        id: el.code,
        name: el.name + (el.legal ? "-" + el.legal : ""),
        deptName: el.name,
        dFiles: el.dFiles || []
      };
    });

    state.formData.projectUnderUnit.forEach(item => {
      state.deptFiles[item.code] = item.dFiles || [];
    });
    // state.fundsTableData = getTableData();
  }
};

const initGetContractList = async (id: number | string) => {
  const { code, data } = await postContractList({ projectManageId: id });
  if (code === 200) {
    state.formData.projectContractDTOList = data.list;
    state.tableData = data.list;
  }
};

// const addMilepost = () => {
//   state.milepostList.push({ name: "", time: "", des1: "", des2: "" });
// };
// const delMilepost = (index: number) => {
//   state.milepostList.splice(index, 1);
// };

// 获取项目类型
const isApproval = route.query.mode === "approval" ? true : false;
const isChange = route.query.mode === "change" ? true : false;
const isStop = route.query.mode === "stop" ? true : false;
// const cantype = route.query.cantype;
initProjectTypeList();
initProjectApprovalTypeList();
initProjectApprovalTypeList2();
initPrincipalCompanyList();
</script>

<style scoped lang="scss">
.card-wrap {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-box-header {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .header-btn {
    font-size: 14px;
    cursor: pointer;
  }
}

.btnClass {
  margin-bottom: 8px;
}

.el-select-dropdown__item {
  height: auto;
  // min-height: 100px;
  // max-height: 274px;
  padding: 0;
  overflow-x: hidden;
  overflow-y: hidden;
}

.el-select-dropdown_item.selected {
  font-weight: normal;
}

.el-select-dropdown_item.selected {
  font-weight: normal;
}

// #tree-option
#tree-option :deep .el-tree-node__content {
  height: auto;
  padding: 0 10px;
}

// #tree-option :deep .el-select-dropdown__list {
//   padding: 0 6px;
// }
#tree-option :deep .el-tree-node__label {
  font-weight: normal;
  padding: 0 10px;
  margin-right: 10px;
}

.el-tree :deep .is-current .el-tree-node__label {
  color: #409eff;
  font-weight: 700;
}

.el-tree :deep .is-current .el-tree-node__children .el-tree-node__label {
  color: #606266;
  font-weight: normal;
}

#default-option :deep .el-tree-node__label {
  font-weight: normal;
  padding: 0 10px;
  // margin-right: 10px;
}

#default-option {
  padding: 0 10px;
}

.des-p {
  color: #a7a3a3;
  font-size: 12px;
}

.milepost-box {
  border: 1px solid #d8dce6;

  .milepost-title {
    position: relative;
    height: 40px;
    line-height: 40px;
    font-size: 14px;
    background: #4f9dff0c;
    text-indent: 16px;
    margin-bottom: 20px;

    .close {
      position: absolute;
      right: 20px;
      top: 12px;
      color: red;
      cursor: pointer;
      font-size: 16px;
    }
  }
}

.p-text {
  line-height: 32px;
  font-size: 14px;
}

:deep .approve-code .el-form-item__content {
  margin: 0 !important;
}
</style>
